import java.util.Arrays;

/**
 * @Author: wanqian
 * @Date: 2021/3/1 2:20
 */
public class KMPAlgorithmDemo {

    public static void main(String[] args) {
        String str = "BBC ABCDABCDABDABCDABDE";
        int index = indexOf(str, "ABCDABD");
        System.out.println(index);
    }

    public static int indexOf(String str1, String str2) {
        int[] next = kmpNext(str2);
        System.out.println(Arrays.toString(next));
        // 遍历
        for (int i = 0, j = 0; i < str1.length(); i++) {

            // 需要处理 str1.charAt(i) ！= str2.charAt(j), 去调整j的大小
            // KMP算法核心点, 可以验证...
            while (j > 0 && str1.charAt(i) != str2.charAt(j)) {
                j = next[j - 1];
            }

            if (str1.charAt(i) == str2.charAt(j)) {
                j++;
            }

            if (j == str2.length()) { // 找到了
                return i - j + 1;
            }
        }
        return -1;
    }

    public static int[] kmpNext(String str) {
        int[] next = new int[str.length()];
        next[0] = 0;
        for (int i = 1, j = 0; i < str.length(); i++) {
            while (j > 0 && str.charAt(i) != str.charAt(j)) {
                j = next[j - 1];
            }

            if (str.charAt(i) == str.charAt(j)) {
                j++;
            }
            next[i] = j;
        }
        return next;
    }
}
